package video

import (
	"fmt"
	"strings"
	"strconv"
	// for parsing sites
	"github.com/gocolly/colly"
	// for terminal ui
	"github.com/rivo/tview"
)

// TUI app
var app = tview.NewApplication()

// Get video link
func GetVideos(url string) (string) {
	list := tview.NewList().ShowSecondaryText(false)
	var hrefVideo string

	c := colly.NewCollector(
		colly.AllowedDomains("y.com.sb"),
	)

	var hrefVideoArray [70]string
	hrefIter := 0
	c.OnHTML(".h-box > a", func ( e *colly.HTMLElement ) {
		hrefVideoArray[hrefIter] = e.Attr("href")
		hrefIter++
	})

	number := 1
	c.OnHTML(".h-box > a > p", func ( e *colly.HTMLElement ) {
		text := strings.TrimSpace(e.Text)
		text  = fmt.Sprintf("%d. %s", number, text)
		list.AddItem(text, "hello", '#', func() {
			app.Stop()
			indexOfVideo, _ := strconv.Atoi(text[:1])
			hrefVideo = fmt.Sprintf("https://y.com.sb%s", hrefVideoArray[indexOfVideo-1])
		})
		number++
	})

	c.Visit(url)

	if err := app.SetRoot(list, true).EnableMouse(true).Run(); err != nil {
		panic(err)
	}

	return hrefVideo
}

